package com.jlz.actions.login.reset;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Standard;
import org.springframework.beans.factory.annotation.Autowired;

import com.jlz.beans.user.LinkBean;
import com.jlz.beans.user.UserBean;
import com.jlz.managers.user.Links;
import com.jlz.managers.user.Users;
import com.jlz.service.email.EmailService;
import com.julewa.Client;
import com.julewa.utils.Patterns;

@Standard
public class IndexAction {
	
	private @Autowired Links links;
	private @Autowired Users users;
	private @Autowired Client client;
	private @Autowired EmailService emailsrv;
	private String email;
	
	@Action("password")
	public String readyPassword(){
		
		return "password";
	}
	
	
	@Action("notice")
	public String resetPassword(){
		email = StringUtils.trimToNull(email);
		if(email == null){
			return "password";
		}
		if(!Patterns.EMAIL.match(email)){
			client.putError("噢,您的邮箱名好像写错了耶~");
			return "password";
		}
		LinkBean link = links.find(email);
		if(link == null){
			client.putError("噢,您好像还没有注册呢~");
			return "password";
		}
		switch(Links.State.of(link.getState())){
		case NEW:
			client.putError("您的账号尚未激活");
			return "password";
		case LOCKED:
			client.putError("噢,这个邮箱不能用,换一个吧~");
			return "password";
		};
		link.setPassword(links.randomPassword());
		links.update(link);
		//
		UserBean user = users.get(link.getUserId());
		emailsrv.sendResetPassword(email, user.getName(), link.getPassword());
		return "notice";
	}
	

	public String getEmail() {
		return email;
	}


	public void setEmail(String email) {
		this.email = email;
	}


}
